package com.guigusuqi.user.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证成功之后，把用户信息封装在LoginUser中
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails
{
    private SysUser user;

    //  当前用户的权限信息
    private List<String> permissions;

    //  权限集合
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    public LoginUser(SysUser user)
    {
        this.user = user;
        this.permissions = null;
    }

    public LoginUser(SysUser user, List<String> permissions)
    {
        this.user = user;
        this.permissions = permissions;
    }

    //  获取权限信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities()
    {
        if(authorities != null)
        {
            return authorities;
        }
        //  第二种方式
        return permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @Override
    public String getPassword()
    {
        return user.getPassword();
    }

    @Override
    public String getUsername()
    {
        return user.getUserId();
    }

    //  是否未过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //  是否未锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //  凭证是否未过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //  是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
